import pymongo as mg
from pymongo.collection import Collection
from typing import Any, Dict, List
from pydantic import BaseModel
from fastapi import APIRouter, Request
import requests
from fastapi.responses import StreamingResponse,Response
import datetime
import asyncio
import json
import time
from core import setting, mgClient

db = mgClient['chat']
collection = db.get_collection('sync')

router = APIRouter(
    prefix="/sync",
    tags=["sync"]
)

@router.get("/getData")
async def getData(userId:int):
    queryResult = collection.find({"userId":userId})
    resultList = [{"id":i["id"],"date":i["date"]} for i in queryResult]
    return resultList
class ChatData(BaseModel):
    tree:Any
    displayNode:Any
@router.post("/insertData")
async def insertData(userId:int,data:ChatData):
    id = 0
    if((collection.count_documents({}))):
        query = collection.find().sort("id",-1).limit(1)[0]
        id = query['id'] + 1
        print(id)
    collection.insert_one({"id":id,"userId":userId,"data":data.__dict__,"date":int(datetime.datetime.now().timestamp()*1000)})
    return {"status":True}
@router.delete("/deleteData")
async def deleteData(userId:int,id:int):
    result = collection.delete_one({"userId":userId,"id":id})
    return {"status":True}
@router.put("/updateData")
async def updateData(userId:int,id:int,data:ChatData):
    query = collection.find_one({"userId":userId,"id":id})
    query['data'] = data.__dict__
    query['date'] = int(datetime.datetime.now().timestamp()*1000)
    collection.update_one({"userId":userId,"id":id},{"$set":query})
    return {"status":True}
@router.get("/download")
async def download(userId:int,id:int):
    query = collection.find({"userId":userId,"id":id}).limit(1)[0]
    return query['data']